import Router from 'koa-router';
import { DefaultAvatar } from '../models/index.js';
import { transformUrls } from '../utils/url.js';

const router = new Router({
  prefix: '/api/default-avatars'
});

// 获取默认头像列表（支持分类和状态筛选）
router.get('/', async (ctx) => {
  try {
    const {
      category,
      status = 'active',
      page = 1,
      pageSize = 20
    } = ctx.query;

    // 构建查询条件
    const where = {};
    if (category) {
      where.category = category;
    }
    if (status) {
      where.status = status;
    }

    // 执行查询
    const { count, rows } = await DefaultAvatar.findAndCountAll({
      where,
      order: [
        ['sort', 'DESC'],
        ['id', 'ASC']
      ],
      limit: parseInt(pageSize),
      offset: (parseInt(page) - 1) * parseInt(pageSize)
    });

    // 转换URL为完整地址
    const transformedRows = transformUrls(rows);


    ctx.body = {
      total: count,
      totalPages: Math.ceil(count / pageSize),
      currentPage: parseInt(page),
      pageSize: parseInt(pageSize),
      list: transformedRows
    };
  } catch (error) {
    console.error('获取默认头像列表失败:', error);
    ctx.throw(500, '获取默认头像列表失败');
  }
});

// 获取指定头像信息
router.get('/:id', async (ctx) => {
  try {
    const { id } = ctx.params;
    const avatar = await DefaultAvatar.findByPk(id);
    
    if (!avatar) {
      ctx.throw(404, '头像不存在');
    }
    
    // 转换URL为完整地址
    ctx.body = transformUrls(avatar);
  } catch (error) {
    console.error('获取头像信息失败:', error);
    ctx.throw(500, '获取头像信息失败');
  }
});

// 创建新的默认头像
router.post('/', async (ctx) => {
  try {
    const { name, url, category, sort } = ctx.request.body;
    
    // 验证必填字段
    if (!name || !url) {
      ctx.throw(400, '名称和URL为必填项');
    }

    // 检查分类是否有效
    const validCategories = ['male', 'female', 'cartoon', 'other'];
    if (category && !validCategories.includes(category)) {
      ctx.throw(400, '无效的头像分类');
    }

    const avatar = await DefaultAvatar.create({
      name,
      url,
      category: category || 'other',
      sort: sort || 0,
      status: 'active'
    });

    // 转换URL为完整地址
    ctx.body = transformUrls(avatar);
    ctx.status = 201;
  } catch (error) {
    console.error('创建默认头像失败:', error);
    ctx.throw(500, '创建默认头像失败');
  }
});

// 更新头像信息
router.put('/:id', async (ctx) => {
  try {
    const { id } = ctx.params;
    const { name, url, category, sort, status } = ctx.request.body;
    
    const avatar = await DefaultAvatar.findByPk(id);
    if (!avatar) {
      ctx.throw(404, '头像不存在');
    }

    // 检查分类是否有效
    if (category) {
      const validCategories = ['male', 'female', 'cartoon', 'other'];
      if (!validCategories.includes(category)) {
        ctx.throw(400, '无效的头像分类');
      }
    }

    // 检查状态是否有效
    if (status) {
      const validStatus = ['active', 'inactive'];
      if (!validStatus.includes(status)) {
        ctx.throw(400, '无效的状态');
      }
    }

    // 更新信息
    await avatar.update({
      name: name || avatar.name,
      url: url || avatar.url,
      category: category || avatar.category,
      sort: sort !== undefined ? sort : avatar.sort,
      status: status || avatar.status
    });

    // 转换URL为完整地址
    ctx.body = transformUrls(avatar);
  } catch (error) {
    console.error('更新头像信息失败:', error);
    ctx.throw(500, '更新头像信息失败');
  }
});

// 删除头像
router.delete('/:id', async (ctx) => {
  try {
    const { id } = ctx.params;
    const avatar = await DefaultAvatar.findByPk(id);
    
    if (!avatar) {
      ctx.throw(404, '头像不存在');
    }

    await avatar.destroy();
    ctx.status = 204;
  } catch (error) {
    console.error('删除头像失败:', error);
    ctx.throw(500, '删除头像失败');
  }
});

// 批量更新排序
router.post('/batch-sort', async (ctx) => {
  try {
    const { sortData } = ctx.request.body;
    
    if (!Array.isArray(sortData)) {
      ctx.throw(400, '无效的排序数据');
    }

    // 批量更新排序
    await Promise.all(
      sortData.map(item => 
        DefaultAvatar.update(
          { sort: item.sort },
          { where: { id: item.id } }
        )
      )
    );

    ctx.body = { message: '排序更新成功' };
  } catch (error) {
    console.error('更新排序失败:', error);
    ctx.throw(500, '更新排序失败');
  }
});

export default router;
